/**
 * Projekt do předmetu GJA - LATEX TABLE CREATOR
 *
 * Soubor: SizeDialog.java
 *
 * @author Ondřej Kubal  <xkluba00@stud.fit.vutbr.cz>
 * @author Petr Šimon    <xsimon10@stud.fit.vutbr.cz>
 */

package table;

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;


/**
 * Dialog pro zadání výšky řádku/šířky sloupce.
 * Poproruje zadávání velikosti v různých jednotkách (mm,cm,pt,pc,in,em,px..).
 */
public class SizeDialog extends javax.swing.JDialog
{

     /**
      * Konstruktor, inicializace
      */
     public SizeDialog(java.awt.Frame parent, boolean modal)
     {
          super(parent, modal);
          initComponents();
          table = null;
          rowHeader = null;
          bWidths = false;
     }
     
     /**
      * Nastaví tabulku, se kterým budeme pracovat
      * @param table hlavní tabulka
      */
     public void setTable(MultiSpanCellTable table)
     {
          this.table = table;
     }
     
     /**
      * Nastaví rowHeader, se kterým budeme pracovat
      * @param table rowHeader
      */
     public void setRowHeader(JTable table)
     {
          this.rowHeader = table;
     }
     
     /**
      * Přepínač/řádky sloupce
      * @param b true, pokud nastavujeme šířku sloupce
      */
     public void setModeWidths(boolean b)
     {
          this.bWidths = b;
     }
     
     /**
      * Index řádku/sloupce pro naštení hodnot do formuláře.
      * @param index
      */
     public void setIndex(int index)
     {
          this.index = index;
     }
     
     /**
      * Zobrazí dialog uprostřed obrazovky.
      * Načte potřebná data.
      * Jediná korektní metoda pro zobrazení dialogu !!!
      */
     public void centerScreen()
     {
          Dimension dim = getToolkit().getScreenSize();
          Rectangle abounds = getBounds();
          setLocation((dim.width - abounds.width) / 2,
                      (dim.height - abounds.height) / 2);
                      
          if (table != null)
          {
               DefaultCellAttribute data = (DefaultCellAttribute)((AttributiveCellTableModel) table.getModel()).getCellAttribute();
               
               if (bWidths)
               {
                    this.jSpinner1.setValue(data.getWidth(index));
                    this.jComboBox1.setSelectedIndex(data.getWidthType(index));
               }
               else
               {
                    this.jSpinner1.setValue(data.getHeight(index));
                    this.jComboBox1.setSelectedIndex(data.getHeightType(index));
               }
          }
          
          this.setVisible(true);
          requestFocus();
     }
     
     
     /** This method is called from within the constructor to
      * initialize the form.
      * WARNING: Do NOT modify this code. The content of this method is
      * always regenerated by the Form Editor.
      */
     @SuppressWarnings("unchecked")
     // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
     private void initComponents()
     {
     
          btOK = new javax.swing.JButton();
          btCancel = new javax.swing.JButton();
          jComboBox1 = new javax.swing.JComboBox();
          jSpinner1 = new javax.swing.JSpinner();
          jLabel1 = new javax.swing.JLabel();
          
          setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
          org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(latextablecreator.LatexTableCreatorApp.class).getContext().getResourceMap(SizeDialog.class);
          setTitle(resourceMap.getString("fSize.title")); // NOI18N
          setAlwaysOnTop(true);
          setModal(true);
          setName("fSize"); // NOI18N
          
          btOK.setText(resourceMap.getString("btOK.text")); // NOI18N
          btOK.setName("btOK"); // NOI18N
          btOK.addActionListener(new java.awt.event.ActionListener()
          {
               public void actionPerformed(java.awt.event.ActionEvent evt)
               {
                    btOKActionPerformed(evt);
               }
          });
          
          btCancel.setText(resourceMap.getString("btCancel.text")); // NOI18N
          btCancel.setName("btCancel"); // NOI18N
          btCancel.addActionListener(new java.awt.event.ActionListener()
          {
               public void actionPerformed(java.awt.event.ActionEvent evt)
               {
                    btCancelActionPerformed(evt);
               }
          });
          
          jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "nezadáno", "px", "cm", "mm", "in", "pt", "pc", "em" }));
          jComboBox1.setToolTipText(resourceMap.getString("jComboBox1.toolTipText")); // NOI18N
          jComboBox1.setName("jComboBox1"); // NOI18N
          jComboBox1.addActionListener(new java.awt.event.ActionListener()
          {
               public void actionPerformed(java.awt.event.ActionEvent evt)
               {
                    jComboBox1ActionPerformed(evt);
               }
          });
          
          jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Float.valueOf(24.0f), Float.valueOf(0.0f), null, Float.valueOf(1.0f)));
          jSpinner1.setName("jSpinner1"); // NOI18N
          jSpinner1.addChangeListener(new javax.swing.event.ChangeListener()
          {
               public void stateChanged(javax.swing.event.ChangeEvent evt)
               {
                    jSpinner1StateChanged(evt);
               }
          });
          
          jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
          jLabel1.setName("jLabel1"); // NOI18N
          
          javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
          getContentPane().setLayout(layout);
          layout.setHorizontalGroup(
               layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addGroup(layout.createSequentialGroup()
                         .addContainerGap()
                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                   .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                             .addComponent(jSpinner1, javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE)
                                             .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                             .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                             .addGap(4, 4, 4))
                                   .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                             .addComponent(btOK)
                                             .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                             .addComponent(btCancel))
                                   .addComponent(jLabel1))
                         .addContainerGap())
          );
          layout.setVerticalGroup(
               layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                         .addContainerGap()
                         .addComponent(jLabel1)
                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                             .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                             .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                                   .addGroup(layout.createSequentialGroup()
                                             .addGap(38, 38, 38)
                                             .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                       .addComponent(btCancel)
                                                       .addComponent(btOK))))
                         .addContainerGap())
          );
          
          pack();
     }// </editor-fold>//GEN-END:initComponents
     
     /**
      * Storno tlačítko - zavře dialog bez uložení změn.
      * @param evt událost (nevyužito)
      */
     private void btCancelActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btCancelActionPerformed
     {
          this.dispose(); //zrušíme dialog
     }//GEN-LAST:event_btCancelActionPerformed
     
     /**
      * OK tlačítko - zavře dialog a uloží změny.
      * Nastaví výšku řádku/šířku sloupce v hlavní tabulce, rowHeaderu a modelu.
      * Přepočítává jednotky na pixely (pouze pro zobrazení).
      * @param evt událost (nevyužito)
      */
     private void btOKActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btOKActionPerformed
     {
          this.setVisible(false);
          
          if (table != null)
          {
               int type = (int) this.jComboBox1.getSelectedIndex();
               float size = (float)((Float) this.jSpinner1.getValue());
               FontMetrics fm = table.getGraphics().getFontMetrics(table.getFont());
               
               DefaultCellAttribute data = (DefaultCellAttribute)((AttributiveCellTableModel) table.getModel()).getCellAttribute();
               
               float sizeOrg = size;
               
               if (type == CellAttribute.SIZE_CM)
               {
                    size *= (getToolkit().getScreenResolution() / 2.54);
               }
               else if (type == CellAttribute.SIZE_MM)
               {
                    size *= (getToolkit().getScreenResolution() / 2.54) / 10.0;
               }
               else if (type == CellAttribute.SIZE_IN)
               {
                    size *= (getToolkit().getScreenResolution());
               }
               else if (type == CellAttribute.SIZE_PT)
               {
                    size *= (getToolkit().getScreenResolution()) / 72.0;
               }
               else if (type == CellAttribute.SIZE_PC)
               {
                    size *= (getToolkit().getScreenResolution()) / 6.0;
               }
               else if (type == CellAttribute.SIZE_EM)
               {
                    size *= fm.charWidth('M');
               }
               
               if (bWidths)
               {
                    int [] cols = table.getSelectedColumns();
                    data.setWidth(index, sizeOrg, type);
                    
                    for (int i = 0; i < cols.length; i++)
                    {
                         data.setWidth(cols[i], sizeOrg, type);
                    }
                    
                    if (type != CellAttribute.SIZE_NONE) //můžeme přenést do tabulky
                    {
                         TableColumn column = table.getColumnModel().getColumn(index);
                         column.setWidth((int) size);
                         column.setPreferredWidth((int) size);
                         
                         for (int i = 0; i < cols.length; i++)
                         {
                              column = table.getColumnModel().getColumn(cols[i]);
                              column.setWidth((int) size);
                              column.setPreferredWidth((int) size);
                         }
                    }
                    
               }
               else
               {
                    int [] rows = table.getSelectedRows();
                    
                    data.setHeight(index, sizeOrg, type);
                    
                    for (int i = 0; i < rows.length; i++)
                    {
                         data.setHeight(rows[i], sizeOrg, type);
                    }
                    
                    if (type != CellAttribute.SIZE_NONE) //můžeme přenést do tabulky
                    {
                         table.setRowHeight(index, (int) size);
                         
                         if (rowHeader != null)  rowHeader.setRowHeight(index, (int) size);
                         
                         
                         for (int i = 0; i < rows.length; i++)
                         {
                              table.setRowHeight(rows[i], (int) size);
                              
                              if (rowHeader != null)  rowHeader.setRowHeight(rows[i], (int) size);
                         }
                    }
               }
               
               table.getTableHeader().repaint();
               table.repaint();
          }
          
          this.dispose(); //zrušíme dialog
     }//GEN-LAST:event_btOKActionPerformed
     
     /**
      * Kontorla správnosti zadaných údajů.
      * @param evt událost (nevyužito)
      */
     private void jSpinner1StateChanged(javax.swing.event.ChangeEvent evt)//GEN-FIRST:event_jSpinner1StateChanged
     {
          float a = (Float) jSpinner1.getValue();
          
          if (a <= 0f) jSpinner1.setValue(1f);
     }//GEN-LAST:event_jSpinner1StateChanged
     
     private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jComboBox1ActionPerformed
     {
          // TODO add your handling code here:
     }//GEN-LAST:event_jComboBox1ActionPerformed
     
     /**
     * @param args the command line arguments
     */
     public static void main(String args[])
     {
          java.awt.EventQueue.invokeLater(new Runnable()
          {
               public void run()
               {
                    SizeDialog dialog = new SizeDialog(new javax.swing.JFrame(), true);
                    dialog.addWindowListener(new java.awt.event.WindowAdapter()
                    {
                         @Override
                         public void windowClosing(java.awt.event.WindowEvent e)
                         {
                              System.exit(0);
                         }
                    });
                    dialog.setVisible(true);
               }
          });
     }
     
     // Variables declaration - do not modify//GEN-BEGIN:variables
     private javax.swing.JButton btCancel;
     private javax.swing.JButton btOK;
     private javax.swing.JComboBox jComboBox1;
     private javax.swing.JLabel jLabel1;
     private javax.swing.JSpinner jSpinner1;
     // End of variables declaration//GEN-END:variables
     
     private MultiSpanCellTable table;
     private JTable rowHeader;
     private boolean bWidths;
     private int index;
}
